﻿using System;
using System.Collections.Generic;
using System.Text;

namespace FlashSolution
{
    public class StringValueAttribute : System.Attribute
    {
        private string _value = null;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="value"></param>
        public StringValueAttribute(string value)
        {
            _value = value;
        }

        /// <summary>
        /// 
        /// </summary>
        public string Value
        {
            get { return _value; }
        }

        private static StringValueAttribute[] GetStringValueAttributes(Type type, Enum value)
        {
            StringValueAttribute[] output = null;

            // Look for our 'StringValueAttribute' in the field's custom attributes
            System.Reflection.FieldInfo fi = type.GetField(value.ToString());
            StringValueAttribute[] attrs = fi.GetCustomAttributes(typeof(StringValueAttribute), false) as StringValueAttribute[];
            if (attrs != null && attrs.Length > 0)
            {
                output = attrs;
            }
            return output;
        }

        private static System.Collections.Hashtable _stringValues = new System.Collections.Hashtable();

        /// <summary>
        /// 
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static string StringFromEnum(Enum value)
        {
            Type type = value.GetType();

            string key = type.FullName + "_" + value.ToString();

            StringValueAttribute[] attrs = null;

            //Check first in our cached results...
            if (_stringValues.ContainsKey(key))
            { // Found!
                attrs = (_stringValues[key] as StringValueAttribute[]);
                _stringValues.Add(key, attrs);
            }
            else
            { // Not found!
                attrs = GetStringValueAttributes(type, value);
            }


            string output = null;
            if (attrs != null && attrs.Length > 0)
            {
                output = attrs[0].Value;
            }

            return output;
        }

    }
}
